/*
 * @features: 主要功能
 * @description: 内容说明
 * @Date: 2021-09-11 16:26:59
 * @Author: judu233(769471424@qq.com)
 * @LastEditTime: 2021-09-12 00:18:13
 * @LastEditors: judu233
 */

import { ProxyOb } from "./ProxyOb";
import VmBase, { EventHandleCall } from "./VmBase";

const { ccclass, property, menu } = cc._decorator;

enum PARAM_TYPE {
    index,
    name
}

@ccclass(`PageHandel`)
class PageHandel extends EventHandleCall {
}

@ccclass(`BtnChange`)
class BtnChange {
    @property({ type: cc.Enum(cc.Button.Transition) })
    transition: cc.Button.Transition = cc.Button.Transition.NONE;

    @property({ visible() { return this.transition === cc.Button.Transition.COLOR } })
    hoverColor: cc.Color = cc.color(255, 255, 255);

    @property({ visible() { return this.transition === cc.Button.Transition.COLOR } })
    normalColor: cc.Color = cc.color(214, 214, 214);

    @property({ visible() { return this.transition === cc.Button.Transition.COLOR } })
    pressedColor: cc.Color = cc.color(211, 211, 211);

    @property({ visible() { return this.transition === cc.Button.Transition.COLOR } })
    disabledColor: cc.Color = cc.color(124, 124, 124);

    @property({ type: cc.SpriteFrame, visible() { return this.transition === cc.Button.Transition.SPRITE } })
    normalSprite: cc.SpriteFrame = null;

    @property({ type: cc.SpriteFrame, visible() { return this.transition === cc.Button.Transition.SPRITE } })
    pressedSprite: cc.SpriteFrame = null;

    @property({ type: cc.SpriteFrame, visible() { return this.transition === cc.Button.Transition.SPRITE } })
    hoverSprite: cc.SpriteFrame = null;

    @property({ type: cc.SpriteFrame, visible() { return this.transition === cc.Button.Transition.SPRITE } })
    disabledSprite: cc.SpriteFrame = null;

    @property({ visible() { return this.transition === cc.Button.Transition.SCALE || this.transition === cc.Button.Transition.COLOR } })
    duration: number = 1.0;

    @property({ visible() { return this.transition === cc.Button.Transition.SCALE } })
    zoomScale: number = 1.1;

    @property({ type: cc.Enum(PARAM_TYPE) })
    paramType: PARAM_TYPE = PARAM_TYPE.index;
}

@ccclass
@menu('VM/VM-Page')
export default class VmPage extends VmBase {

    @property({ displayName: `是否是循环页面` })
    isLoopPage: boolean = false;

    /**上一个index */
    private preIndex: number = -1;

    /**当前index */
    @property
    private _index: number = 0;
    public get index(): number { return this._index; }
    @property({ type: cc.Integer })
    public set index(v: number) {
        if (this.isChanging) return;
        v = this.checkIndex(v);
        this.preIndex = this._index;//标记之前的页面
        this._index = v;
        this.updatePage(v);
    }

    @property({ displayName: `遍历子节点`, tooltip: `遍历子节点绑定切换页面` })
    forEachChild = true;

    @property({ displayName: `影响的节点`, type: [cc.Node], visible() { return !this.forEachChild } })
    userTarget: cc.Node[] = [];

    /**实际影响的目标 */
    _target: cc.Node[] = [];

    //判断是否在 changing 页面状态
    private _isChanging: boolean = false;
    public get isChanging(): boolean { return this._isChanging; }

    onValueInit() {
        this._target = this.forEachChild ? this.node.children : this.userTarget;
        this._target.forEach(node => node.active = false);
        this.bindToggoleNode();
        this.index = ProxyOb.getValue(this.watchPath);
        this.updatePage(this.index);
    }


    /**检查Index是否符合 */
    checkIndex(v) {
        let count = this._target.length - 1;
        v = Math.round(v);
        if (this.isLoopPage) {
            if (v > count) v = 0;
            if (v < 0) v = count;
        } else {
            if (v > count) v = count;
            if (v < 0) v = 0;
        }
        return v;
    }

    /**更新切换 */
    private updatePage(page: number) {
        if (CC_EDITOR) {
            this._target = this.forEachChild ? this.node.children : this.userTarget;
            for (let [i, node] of this._target.entries()) {
                node.active = (i == page);
            }
        } else {
            try {
                if (this.preIndex === this.index) return;//没有改变就不进行操作
                if (this.preIndex != -1)
                    this._target[this.preIndex].active = false;
                this._target[this.index].active = true;
            } catch (error) {
                cc.error(`设置按钮参数错误，index查找失败`);
            }
        }
    }

    /**快速切换下一页 */
    public fast_next() {
        if (this.isChanging) {
            return false;
        } else {
            this.index++;
            return true;
        }
    }

    /**快速切换上一页 */
    public fast_previous() {
        if (this.isChanging) {
            return false;
        } else {
            this.index--;
            return true;
        }
    }

    /*按钮设置， 或事件设置 */
    public setEventIndex(e, index) {
        if (this.index >= 0 && this.index != null && !this.isChanging) {
            this.index = index;
            return true;
        } else {
            return false;
        }
    }

    @property({ displayName: `切换按钮设置`, type: BtnChange })
    btnChangeSet: BtnChange = new BtnChange();

    @property({ displayName: `切换按钮回调`, type: PageHandel })
    touchEventsHandle: PageHandel = new PageHandel();

    @property({ displayName: `按钮节点的父节点`, tooltip: `切换按钮组的父节点`, type: cc.Node })
    btnNodeList: cc.Node = null;



    /**绑定切换按钮 */
    bindToggoleNode() {
        this.btnNodeList?.children.forEach((node, nodeIndex) => {
            let comp = node.getComponent(cc.Button) ?? node.addComponent(cc.Button);
            comp.transition = this.btnChangeSet.transition;
            //同步属性
            if (this.btnChangeSet.transition == cc.Button.Transition.SCALE) {
                comp.target = node;
                comp.transition = this.btnChangeSet.transition;
                comp.zoomScale = this.btnChangeSet.zoomScale;
            } else {
                comp.target = node.getComponent(cc.Sprite)?.node
                    ?? node.getComponentInChildren(cc.Sprite)?.node;
                if (this.btnChangeSet.transition == cc.Button.Transition.COLOR) {
                    comp.hoverColor = this.btnChangeSet.hoverColor;
                    comp.normalColor = this.btnChangeSet.normalColor;
                    comp.pressedColor = this.btnChangeSet.pressedColor;
                    comp.disabledColor = this.btnChangeSet.disabledColor;
                } else {
                    comp.disabledSprite = this.btnChangeSet.disabledSprite;
                    comp.hoverSprite = this.btnChangeSet.hoverSprite;
                    comp.normalSprite = this.btnChangeSet.normalSprite;
                    comp.pressedSprite = this.btnChangeSet.pressedSprite;
                }
            }

            //绑定回调事件
            this.touchEventsHandle.compEvents.forEach((event) => {
                //克隆数据，每个节点获取的都是不同的回调
                let hd = new cc.Component.EventHandler();//copy对象
                hd.target = event.target;
                hd.handler = event.handler;
                hd.component = event.component;
                hd['_componentId'] = event['_componentId'];

                if (this.btnChangeSet.paramType === PARAM_TYPE.index) {
                    hd.customEventData = nodeIndex.toString();
                } else {
                    hd.customEventData = node.name;
                }
                comp.clickEvents.push(hd);
            });
        });
    }
}
